import IconFont from "@/components/IconFont";
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { CommonModal } from "@/views/components/CommonModal";
import CommonText from "@/pages/OrderModule/common/components/CommonText/CommonText";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import FieldWrapper from "@/pages/OrderModule/orderList/components/Filter/components/FieldWrapper";
import { DoubleLeftOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import { message, Checkbox, Collapse, Form, Radio, Select, Tabs, Tooltip, Space, Popover, Row, Col } from "antd";
import { useEffect, useRef, useState } from "react";
import FormRowWrapper from "../FormRowWrapper/index";
import CommonLoading from "@/components/CommonLoading";
import SelectTag from "@/components/SelectTag";
import { warehouseSelectList, labelStrategySaveOp, labelStrategyGetById, updateLabelStrategyOp } from "../../service";
import { isEmpty, isNil, find } from "lodash";
import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import Style from "./index.module.less";
import SelectErrorModal from "./SelectErrorModal";
import SelectShop from "@/components/SelectShop";
import GoodsSelectModal from "@/pages/OrderModule/common/bizcomponents/GoodsSelectModal";
import BatchInputModal from "@/pages/OrderModule/common/components/BatchInputModal2";
import Iconfont from "@/components/IconFont";
import { labelTypeMap, labelColorMap } from "@/utils/config";
import { getAllowClearProps } from "../../helpers/constant";
import AreaSelect from "@/components/AreaSelect";
import { getAllArea } from "@/services/common";

const { Option } = Select;

//旗帜
const checkboxList = [
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihong"></IconFont>} />,
		value: 1
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihuang"></IconFont>} />,
		value: 2
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilv"></IconFont>} />,
		value: 3
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilan"></IconFont>} />,
		value: 4
	},

	{
		label: <CommonText extractIcon={<IconFont type="iconqizhizi"></IconFont>} />,
		value: 5
	}
];

const formCategoryList = [
	{
		key: "intelligent-form__ruleName",
		title: "规则名称",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	},
	{
		key: "intelligent-form__processMethod",
		title: "处理方式",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle
						title={
							<div style={{ display: "flex", alignItems: "center" }}>
								{this.title}
								<div style={{ display: "flex", fontWeight: 300, fontSize: 12 }}>
									（最少设置一个）
									<div style={{ color: "var(--color-info)" }}>
										<Popover
											content={
												<div>
													<div>1、订单标签：多个标签都满足的话，则标签会累加显示</div>
													<div>2、标异常：按最高优先级的规则来标记</div>
													<div>3、设置发货仓：按最高优先级的规则来设置</div>
												</div>
											}
										>
											<div>
												<QuestionCircleOutlined />
											</div>
										</Popover>
									</div>
								</div>
							</div>
						}
						as="s2"
						symbol
					/>
					{node}
				</div>
			);
		}
	},
	{
		key: "intelligent-form__orderCondition",
		title: "订单条件",
		render(node) {
			return (
				<div style={{ marginBottom: "16px" }} id={this.key}>
					<SubTitle
						title={
							<>
								{this.title}
								<span style={{ fontWeight: 300, fontSize: 12 }}>（不同条件之间需要都满足）</span>
							</>
						}
						as="s2"
						symbol
					/>
					{node}
				</div>
			);
		}
	}
];

//弹窗标题
const titleMap = {
	add: "新增",
	edit: "编辑"
};

const AddNewModal = ({ visible, type, recordData, handleCancel, handleOk }) => {
	const [tab, setTab] = useState(formCategoryList[0].key);
	const formWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(formWrapperRef, anchorItems);
	const [labelVisible, setLabelVisible] = useState(false); //是否展示标签弹窗
	const [selectLabels, setSelectLabels] = useState([]); //选择订单标签
	const [warehouse, setWarehouse] = useState([]); //仓库下拉
	const [detailData, setDetailData] = useState({}); //详情数据
	const [errorVisible, setErrorVisible] = useState(false); //选择异常弹窗
	const [selectError, setSelectError] = useState({}); //选择异常类型
	const [shopVisible, setShopVisible] = useState(false); //店铺组件弹窗
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [goodsSelectInfo, setGoodsSelectInfo] = useState({
		//新增商品弹窗
		type: "",
		name: "",
		visible: false,
		spuCodes: [],
		goodsCodes: [],
		notParticipateSpuCodes: [],
		notParticipateGoodsCodes: []
	});
	const [batchInfo, setBatchInfo] = useState({
		visible: false,
		label: "",
		name: ""
	}); //批量输入弹窗
	const [orderLimit, setOrderLimit] = useState({
		orderAmount: false,
		goodsNum: false,
		orderWeight: false,
		goodsPriceSpread: false
	}); //订单金额是否能提交
	const [loading, setLoading] = useState(false);

	const [provinceList, setProvinceList] = useState([]); // 选择省市区
	const [addressData, setAddressData] = useState([]); // 省市区数据

	const [form] = Form.useForm();

	const buyerMessageRule = Form.useWatch("buyerMessageRule", form);
	const sellerMessageRule = Form.useWatch("sellerMessageRule", form);
	const flagRule = Form.useWatch("flagRule", form);

	const minOrderAmountValue = Form.useWatch("minOrderAmount", form);
	const maxOrderAmountValue = Form.useWatch("maxOrderAmount", form);
	const minGoodsNumValue = Form.useWatch("minGoodsNum", form);
	const maxGoodsNumValue = Form.useWatch("maxGoodsNum", form);
	const minOrderWeightValue = Form.useWatch("minOrderWeight", form);
	const maxOrderWeightValue = Form.useWatch("maxOrderWeight", form);
	const minGoodsPriceSpreadValue = Form.useWatch("minGoodsPriceSpread", form);
	const maxGoodsPriceSpreadValue = Form.useWatch("maxGoodsPriceSpread", form);

	useEffect(() => {
		if (!isNil(minOrderAmountValue) && !isNil(maxOrderAmountValue) && minOrderAmountValue > maxOrderAmountValue) {
			setOrderLimit({
				...orderLimit,
				orderAmount: true
			});
		} else {
			setOrderLimit({
				...orderLimit,
				orderAmount: false
			});
		}
	}, [minOrderAmountValue, maxOrderAmountValue]);

	useEffect(() => {
		if (!isNil(minGoodsNumValue) && !isNil(maxGoodsNumValue) && minGoodsNumValue > maxGoodsNumValue) {
			setOrderLimit({
				...orderLimit,
				goodsNum: true
			});
		} else {
			setOrderLimit({
				...orderLimit,
				goodsNum: false
			});
		}
	}, [minGoodsNumValue, maxGoodsNumValue]);

	useEffect(() => {
		if (!isNil(minOrderWeightValue) && !isNil(maxOrderWeightValue) && minOrderWeightValue > maxOrderWeightValue) {
			setOrderLimit({
				...orderLimit,
				orderWeight: true
			});
		} else {
			setOrderLimit({
				...orderLimit,
				orderWeight: false
			});
		}
	}, [minOrderWeightValue, maxOrderWeightValue]);

	useEffect(() => {
		if (
			!isNil(minGoodsPriceSpreadValue) &&
			!isNil(maxGoodsPriceSpreadValue) &&
			minGoodsPriceSpreadValue > maxGoodsPriceSpreadValue
		) {
			setOrderLimit({
				...orderLimit,
				goodsPriceSpread: true
			});
		} else {
			setOrderLimit({
				...orderLimit,
				goodsPriceSpread: false
			});
		}
	}, [minGoodsPriceSpreadValue, maxGoodsPriceSpreadValue]);

	useEffect(() => {
		if (visible) {
			getWarehouseSelectList();
			form.resetFields();
			if (!isEmpty(recordData)) {
				getLabelStrategyGetById();
				getAreaData();
			}
		}
	}, [visible, recordData]);

	//处理出省名称即可
	const formatNameField = list => {
		list.map(province => {
			const obj = find(addressData, ["id", province.id]);
			if (obj) {
				province.name = obj.name;
			}
		});
		return list;
	};

	useEffect(() => {
		if (!isEmpty(addressData)) {
			if (!isEmpty(detailData)) {
				form.resetFields();
				if (detailData.labelConfigList) {
					setSelectLabels(detailData.labelConfigList);
				}
				setSelectError(detailData.errorConfig);
				if (detailData.ecStoreList) {
					setSelectShops(detailData.ecStoreList);
				}
				if (detailData.provinceList) {
					setProvinceList(formatNameField(detailData.provinceList));
				}
			}
		}
	}, [addressData, detailData]);

	useEffect(() => {
		formCategoryList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
	}, [visible]);

	useEffect(() => {
		if (currentAnchor) {
			setTab(currentAnchor);
		}
	}, [currentAnchor]);
	useEffect(() => {
		if (selectLabels.length) {
			form.setFieldsValue({
				labelIds: selectLabels.map(item => (labelTypeMap[item.name] ? labelColorMap[item.name] : item.name)).join(",")
			});
		} else {
			form.setFieldsValue({ labelIds: "" });
		}
	}, [selectLabels]);

	useEffect(() => {
		if (provinceList.length) {
			form.setFieldsValue({
				provinceList: "已选择" + provinceList.map(item => `${item.name}(${item.childs.length})`).join("、")
			});
		} else {
			form.setFieldsValue({ provinceList: "" });
		}
	}, [provinceList]);

	useEffect(() => {
		if (!isEmpty(selectError)) {
			form.setFieldsValue({ errorId: selectError.name });
		} else {
			form.setFieldsValue({ errorId: "" });
		}
	}, [selectError]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	//智能标签详情
	const getLabelStrategyGetById = async () => {
		setLoading(true);
		setDetailData({});
		const { success, data = {} } = await labelStrategyGetById({
			id: recordData.id
		});
		if (success) {
			setDetailData(data);
		}
		setLoading(false);
	};

	//获取省市区地址信息
	const getAreaData = async () => {
		const { data, success } = await getAllArea();
		if (success) {
			setAddressData(data);
		}
	};

	// 去除参数的某个字段
	const removeFieldName = (arr, fieldName) => {
		return arr.map(item => {
			const newNode = { ...item };
			delete newNode[fieldName];
			if (newNode.childs) {
				newNode.childs = removeFieldName(newNode.childs, fieldName);
			}
			return newNode;
		});
	};

	//新增/编辑智能标签规则
	const labelStrategySave = async val => {
		setLoading(true);
		let res;
		const params = {
			...val,
			ecStoreIds: selectShops.length > 0 ? selectShops.map(item => item.id).join(",") : undefined,
			labelIds: selectLabels.length > 0 ? selectLabels.map(item => item.id).join(",") : undefined,
			flags: !isNil(val.flags) ? val.flags.join(",") : undefined,
			errorId: !isEmpty(selectError) ? selectError.id : undefined,
			provinceList: provinceList.length > 0 ? removeFieldName(provinceList, "name") : []
		};
		if (type == "add") {
			res = await labelStrategySaveOp(params);
		} else {
			params.id = recordData.id;
			res = await updateLabelStrategyOp(params);
		}
		const { success, msg = "" } = res;
		if (success) {
			message.success(msg);
			handleOk();
		}
		setLoading(false);
	};

	//仓库下拉选择
	const getWarehouseSelectList = async () => {
		setLoading(true);
		const { success, data = [] } = await warehouseSelectList();
		if (success) {
			setWarehouse(data);
		}
		setLoading(false);
	};

	const showModal = (name, type) => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			type,
			name,
			visible: true
		});
	};

	//选择商品
	const handleGoodsSelect = data => {
		setGoodsSelectInfo({
			...goodsSelectInfo,
			[goodsSelectInfo.name]: data,
			visible: false
		});
		const val = ["spuCodes", "notParticipateGoodsCodes"].includes(goodsSelectInfo.name)
			? data.map(v => v.spuCode)
			: data.map(v => v.skuCode);
		form.setFieldsValue({
			[goodsSelectInfo.name]: val.join()
		});
	};

	const onFinish = () => {
		form
			.validateFields()
			.then(val => {
				const { deliveryWarehouseId, errorId, labelIds } = val;
				//订单金额需要都符合条件
				if (!orderLimit.goodsNum && !orderLimit.goodsPriceSpread && !orderLimit.orderAmount && !orderLimit.orderWeight) {
					if (errorId || deliveryWarehouseId || labelIds) {
						labelStrategySave(val);
					} else {
						message.info("至少设置1个处理方式");
					}
				}
			})
			.catch(err => {});
	};
	const onFinishFailed = errorInfo => {
		console.log("Failed:", errorInfo);
	};

	const renderFirstCollapsePanel = () => {
		return (
			<Collapse.Panel header="1.基础信息" key="1">
				{FormRowWrapper([
					<Form.Item style={{ marginTop: 0 }} name="ecStoreIds">
						<CommonInput
							// readOnly
							allowClear
							onClick={() => setShopVisible(true)}
							onChange={e => handleClear(e, "store")}
							placeholder="请选择店铺"
							suffix={<IconFont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
						/>
					</Form.Item>
				])}
				<Form.Item name="buyerMessageRule" label="买家留言">
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有留言</Radio>
						<Radio value={3}>包含以下留言</Radio>
					</Radio.Group>
				</Form.Item>

				{buyerMessageRule == 3 ? (
					<Form.Item name="buyerMessage" wrapperCol={{ offset: 2 }}>
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={100}
							placeholder="请输入留言备注关键字，以逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多100个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>
				) : (
					""
				)}
				<Form.Item name="sellerMessageRule" label="卖家备注">
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有备注</Radio>
						<Radio value={3}>包含以下备注</Radio>
					</Radio.Group>
				</Form.Item>
				{sellerMessageRule == 3 ? (
					<Form.Item name="sellerMessage" wrapperCol={{ offset: 2 }}>
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={100}
							placeholder="请输入留言备注关键字，以逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多100个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>
				) : (
					""
				)}

				<Form.Item name="flagRule" label="旗帜" labelCol={{ span: 2 }}>
					<Radio.Group>
						<Radio value={1}>不判断</Radio>
						<Radio value={2}>有备注</Radio>
						<Radio value={3}>包含以下旗帜</Radio>
					</Radio.Group>
				</Form.Item>
				{flagRule == 3 ? (
					<Form.Item name="flags" wrapperCol={{ offset: 2 }}>
						<Checkbox.Group style={{ width: "100%" }}>
							<Space direction="horizontal">
								{checkboxList.map(item => (
									<Checkbox key={item.value} value={item.value + ""}>
										{item.label}
									</Checkbox>
								))}
							</Space>
						</Checkbox.Group>
					</Form.Item>
				) : (
					""
				)}
			</Collapse.Panel>
		);
	};

	const renderSecondCollapsePanel = () => {
		return (
			<Collapse.Panel header="2.收件信息" key="2">
				{FormRowWrapper([
					<Form.Item name="buyerAccounts">
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="买家账号，以逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>,
					<Form.Item name="buyerNames">
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="买家姓名，以逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>,
					<Form.Item name="buyerPhones">
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="买家手机号，以逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>,
					// <Form.Item name="buyerProvinces">
					// 	<BatchSuffixInput
					// 		clearable
					// 		allowClear
					// 		autoMultiLine
					// 		modalProps={{
					// 			title: "批量输入"
					// 		}}
					// 		maxItem={500}
					// 		placeholder="省份，以逗号隔开"
					// 		message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
					// 		areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					// 	/>
					// </Form.Item>,
					// <Form.Item name="buyerCities">
					// 	<BatchSuffixInput
					// 		clearable
					// 		allowClear
					// 		autoMultiLine
					// 		modalProps={{
					// 			title: "批量输入"
					// 		}}
					// 		maxItem={500}
					// 		placeholder="城市，以逗号隔开"
					// 		message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
					// 		areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					// 	/>
					// </Form.Item>,
					// <Form.Item name="buyerDistricts">
					// 	<BatchSuffixInput
					// 		clearable
					// 		allowClear
					// 		autoMultiLine
					// 		modalProps={{
					// 			title: "批量输入"
					// 		}}
					// 		maxItem={500}
					// 		placeholder="区县，以逗号隔开"
					// 		message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
					// 		areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					// 	/>
					// </Form.Item>,
					<Form.Item name="provinceList">
						<AreaSelect
							page="common-address-provinceList"
							initSelectData={provinceList}
							handleChange={(_, treeData) => setProvinceList(treeData)}
							onChange={() => setProvinceList([])}
						/>
					</Form.Item>
				])}
				<Form.Item name="buyerAddresses">
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						modalProps={{
							title: "批量输入"
						}}
						maxItem={500}
						placeholder="详细地址，以逗号隔开"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						showType="area"
					/>
				</Form.Item>
			</Collapse.Panel>
		);
	};

	const renderThirdCollapsePanel = () => {
		return (
			<Collapse.Panel
				header={
					<>
						3.订单商品<span style={{ fontWeight: 300, fontSize: 12 }}>（以下3个字段是“或”的关系）</span>
					</>
				}
				key="3"
			>
				{FormRowWrapper([
					<Form.Item name="goodsNames">
						<BatchSuffixInput
							clearable
							allowClear
							autoMultiLine
							modalProps={{
								title: "批量输入"
							}}
							maxItem={500}
							placeholder="请输入包含商品名称关键词，多个逗号隔开"
							message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
							areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
						/>
					</Form.Item>,
					<Form.Item name="goodsCodes">
						<CommonInput
							placeholder="请输入指定商品编码，多个商品编码逗号隔开"
							allowClear
							suffix={
								<>
									<Iconfont type="iconmodal-input" onClick={() => showModal("goodsCodes", "AccordingStyle")} />
									<Iconfont
										type="icondirect-input"
										onClick={() => setBatchInfo({ visible: true, label: "商品编码", name: "goodsCodes" })}
									/>
								</>
							}
						/>
					</Form.Item>,
					<Form.Item name="spuCodes">
						<CommonInput
							placeholder="请输入指定款式编码，多个款式编码逗号隔开"
							allowClear
							suffix={
								<>
									<Iconfont type="iconmodal-input" onClick={() => showModal("spuCodes", "NoNumberInput")} />
									<Iconfont
										type="icondirect-input"
										onClick={() => setBatchInfo({ visible: true, label: "款式编码", name: "spuCodes" })}
									/>
								</>
							}
						/>
					</Form.Item>
				])}
			</Collapse.Panel>
		);
	};

	const renderFourthCollapsePanel = () => {
		const renderInputNumber = (label, code, field1, field2, min = -Infinity, max = 999999, precision = "2") => {
			const numberInputProps = {
				controls: false,
				min,
				max,
				precision,
				placeholder: "请输入",
				style: { backgroundColor: "transparent", boxShadow: "none", marginLeft: 12 }
			};
			const minValue = form.getFieldValue(field1),
				maxValue = form.getFieldValue(field2);
			return (
				<>
					<FieldWrapper
						label={label}
						labelHigh={minValue || maxValue ? true : false}
						childrenStyle={{ display: "flex" }}
						style={{ marginTop: 16, paddingLeft: 12 }}
					>
						<Form.Item noStyle>
							<Form.Item
								// noStyle
								style={{ display: "inline-block", width: "calc(50% - 8px)", margin: "0 8px" }}
								name={field1}
								// rules={[{ validator: validateRange }]}
							>
								<CommonInputNumber {...numberInputProps} allowClearProps={getAllowClearProps(form, field1)} />
							</Form.Item>
							<i className="connector" />
							<Form.Item
								style={{ display: "inline-block", width: "calc(50% - 8px)", margin: "0 8px" }}
								name={field2}
								// rules={[{ validator: validateRange }]}
							>
								<CommonInputNumber {...numberInputProps} allowClearProps={getAllowClearProps(form, field2)} />
							</Form.Item>
						</Form.Item>
					</FieldWrapper>
					{orderLimit[code] ? <span className={Style.isLimitNum}>前面数值必须小于等于后面数值</span> : ""}
				</>
			);
		};
		return (
			<Collapse.Panel header="4.订单金额" key="4">
				<div style={{ marginBottom: -16 }}></div>
				{FormRowWrapper([
					renderInputNumber("订单金额", "orderAmount", "minOrderAmount", "maxOrderAmount"),
					renderInputNumber("商品数量", "goodsNum", "minGoodsNum", "maxGoodsNum", 0, Infinity, "-1"),
					renderInputNumber("订单重量", "orderWeight", "minOrderWeight", "maxOrderWeight", 0, 999999, "3"),
					renderInputNumber("拿货价与售卖价差价", "goodsPriceSpread", "minGoodsPriceSpread", "maxGoodsPriceSpread", -999999)
					// <div style={{ marginTop: 20, color: "var(--color-info)" }}>
					// 	<Tooltip title="拿货价与售卖价差价：会在拿货成功后再判断差价范围、显示标签">
					// 		<QuestionCircleOutlined />
					// 	</Tooltip>
					// </div>
				])}
			</Collapse.Panel>
		);
	};

	//清除店铺/标签弹窗
	const handleClear = (e, code) => {
		const val = e.target.value;
		if (val == "") {
			if (code == "store") {
				setSelectShops([]);
			} else if (code == "orderTag") {
				setSelectLabels([]);
			} else {
				setSelectError({});
			}
		}
	};

	//标签弹窗
	const SelectTagProps = {
		selectLabels: selectLabels.map(item => item.id),
		showFilterMethod: false,
		handleCancel() {
			setLabelVisible(false);
		},
		handleDealData(selectTag, realData) {
			const arr = [];
			selectTag.forEach(item => {
				const obj = find(realData, ["id", item]);
				arr.push(obj);
			});
			return arr;
		},
		handleOK(val) {
			setLabelVisible(false);
			setSelectLabels(val);
		}
	};

	//选择异常弹窗
	const SelectErrorModalProps = {
		item: selectError,
		handleCancel() {
			setErrorVisible(false);
		},
		handleOk(val) {
			setSelectError(val);
			setErrorVisible(false);
		}
	};

	//店铺组件
	const SelectShopProps = {
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	//仓库下拉多选
	const optionWarehouse =
		!isEmpty(warehouse) &&
		warehouse.map(d => (
			<Option key={d.id} value={d.id + ""}>
				{d.warehouseName}({d.isOpen ? "代发" : "自发"})
			</Option>
		));

	//选择商品组件
	const changeGoodsModalProps = {
		hiddenGoodNum: true,
		hiddenExtra: goodsSelectInfo.type == "NoNumberInput" ? true : false,
		type: goodsSelectInfo.type,
		submitCallback(changedArr) {
			handleGoodsSelect(changedArr);
		},
		handleCancel() {
			setGoodsSelectInfo({
				...goodsSelectInfo,
				visible: false
			});
		},
		setSelectedRows(data, rowKey) {
			return goodsSelectInfo[goodsSelectInfo.name].map(v => v[rowKey]) || [];
		}
	};

	//批量输入弹窗
	const BatchInputModalProps = {
		...batchInfo,
		handleCancel() {
			setBatchInfo({
				...batchInfo,
				visible: false
			});
		},
		handleOk(val) {
			form.setFieldsValue({
				[batchInfo.name]: val
			});
			setBatchInfo({
				...batchInfo,
				visible: false
			});
		}
	};

	return (
		<CommonModal
			title={{ title: `${titleMap[type]}智能标签规则` }}
			open={visible}
			onCancel={handleCancel}
			onOk={() => {
				form.submit();
			}}
			width={833}
			destroyOnClose
			okText="保存"
		>
			<div className={Style["modal-content"]}>
				<Tabs
					activeKey={tab}
					onChange={val => {
						scrollToAnchor(val);
					}}
				>
					{formCategoryList.map(item => (
						<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
					))}
				</Tabs>
				<div ref={formWrapperRef} className={Style["modal-form"]}>
					<Form
						form={form}
						initialValues={{
							...detailData,
							flags: detailData.flags ? detailData.flags.split(",") : undefined,
							buyerMessageRule: detailData.buyerMessageRule || 1,
							sellerMessageRule: detailData.sellerMessageRule || 1,
							flagRule: detailData.flagRule || 1,
							deliveryWarehouseId: detailData.deliveryWarehouseId ? detailData.deliveryWarehouseId + "" : undefined
						}}
						onFinish={onFinish}
						onFinishFailed={onFinishFailed}
						autoComplete="off"
						layout="horizontal"
						labelAlign="right"
					>
						{formCategoryList[0].render()}
						{FormRowWrapper([
							<Form.Item name="name" rules={[{ required: true, message: "必填，请输入标签规则名称" }]}>
								<CommonInput placeholder="必填，请输入标签规则名称" maxLength={30} showCount aria-required allowClear />
							</Form.Item>,
							<Form.Item
								name="level"
								rules={[
									{ required: true, message: "必填，请输入优先级" },
									{
										pattern: /^[1-9]\d*$/g,
										message: "请输入正整数"
									}
								]}
							>
								<CommonInputNumber
									placeholder="必填，优先级"
									aria-required
									min={1}
									max={100}
									allowClearProps={getAllowClearProps(form)}
								/>
							</Form.Item>
						])}
						{formCategoryList[1].render()}
						{FormRowWrapper([
							<Form.Item name="labelIds">
								<CommonInput
									// {...inputProps}
									allowClear
									onChange={e => handleClear(e, "orderTag")}
									onClick={() => setLabelVisible(true)}
									// readOnly
									placeholder="请选择订单标签"
									suffix={<IconFont onClick={() => setLabelVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
								/>
							</Form.Item>,
							<Form.Item name="errorId">
								<CommonInput
									allowClear
									onClick={() => setErrorVisible(true)}
									placeholder="请选择异常"
									onChange={e => handleClear(e, "error")}
									// readOnly
									suffix={<IconFont onClick={() => setErrorVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
								/>
							</Form.Item>,
							<Form.Item name="deliveryWarehouseId">
								<Select showSearch placeholder="请选择仓库" optionFilterProp="children" allowClear={true}>
									{optionWarehouse}
								</Select>
							</Form.Item>
						])}

						{formCategoryList[2].render()}
						<Collapse
							defaultActiveKey={["1", "2", "3", "4"]}
							ghost
							// style={{ marginTop: 16 }}
							expandIcon={({ isActive }) => (
								<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
							)}
							expandIconPosition="end"
							className={Style["reset-collapse"]}
						>
							{renderFirstCollapsePanel()}
							{renderSecondCollapsePanel()}
							{renderThirdCollapsePanel()}
							{renderFourthCollapsePanel()}
						</Collapse>
					</Form>
				</div>
			</div>
			{labelVisible && <SelectTag {...SelectTagProps} />}
			{errorVisible && <SelectErrorModal {...SelectErrorModalProps} />}
			{shopVisible && <SelectShop {...SelectShopProps} />}
			{goodsSelectInfo.visible && <GoodsSelectModal {...changeGoodsModalProps} />}
			{batchInfo.visible && <BatchInputModal {...BatchInputModalProps} />}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default AddNewModal;
